package com.cowmooed.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

/**
 * MD5工具类
 * 提供MD5加密相关功能
 */
@Slf4j
public class MD5Util {

    private static final String MD5 = "MD5";
    
    /**
     * MD5加密方法
     * @param str 需要加密的字符串
     * @return 加密后的十六进制字符串
     */
    public static String encrypt(String str) {
        if (str == null) {
            return null;
        }
        
        try {
            MessageDigest md5 = MessageDigest.getInstance(MD5);
            byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
            return byteArrayToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5 encryption failed", e);
            throw new RuntimeException("MD5 encryption failed", e);
        }
    }
    
    /**
     * 将字节数组转换为十六进制字符串
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
    

}